// pages/role-setup/index.js
Page({
  data: {
    selectedRole: '', // 'admin' 或 'partner'
    adminPassword: '',
    confirmPassword: '',
    showPasswordInput: false,
    loading: false
  },

  onLoad() {
    // 检查是否已经设置过角色
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.role) {
      // 已设置过，跳转到首页
      wx.reLaunch({
        url: '/pages/home/index'
      });
    }
  },

  // 选择角色
  onSelectRole(e) {
    const role = e.currentTarget.dataset.role;
    this.setData({
      selectedRole: role,
      showPasswordInput: role === 'admin'
    });
  },

  // 密码输入
  onPasswordInput(e) {
    this.setData({
      adminPassword: e.detail.value
    });
  },

  // 确认密码输入
  onConfirmPasswordInput(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  // 完成设置
  async onCompleteSetup() {
    const { selectedRole, adminPassword, confirmPassword } = this.data;
    
    if (!selectedRole) {
      wx.showToast({
        title: '请选择角色',
        icon: 'none'
      });
      return;
    }

    // 如果是管理员，需要设置密码
    if (selectedRole === 'admin') {
      if (!adminPassword) {
        wx.showToast({
          title: '请设置管理密码',
          icon: 'none'
        });
        return;
      }
      
      if (adminPassword !== confirmPassword) {
        wx.showToast({
          title: '两次密码不一致',
          icon: 'none'
        });
        return;
      }
      
      if (adminPassword.length < 6) {
        wx.showToast({
          title: '密码至少6位',
          icon: 'none'
        });
        return;
      }
    }

    this.setData({ loading: true });

    try {
      // 调用后端接口设置角色
      const userInfo = wx.getStorageSync('userInfo') || {};
      const response = await this.setupUserRole({
        userId: userInfo.id,
        role: selectedRole,
        password: selectedRole === 'admin' ? adminPassword : null
      });

      if (response.success) {
        // 更新本地用户信息
        const updatedUserInfo = {
          ...userInfo,
          role: selectedRole,
          isFirstTime: false
        };
        wx.setStorageSync('userInfo', updatedUserInfo);
        
        // 设置主题
        const theme = selectedRole === 'admin' ? 'admin' : 'partner';
        wx.setStorageSync('currentTheme', theme);
        
        wx.showToast({
          title: '设置成功',
          icon: 'success'
        });
        
        // 跳转到首页
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/home/index'
          });
        }, 1500);
      } else {
        throw new Error(response.message || '设置失败');
      }
    } catch (error) {
      console.error('角色设置失败:', error);
      wx.showToast({
        title: error.message || '设置失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 调用后端接口设置用户角色
  setupUserRole(data) {
    return new Promise((resolve, reject) => {
      const app = getApp();
      const baseUrl = app.globalData.baseUrl || 'http://localhost:8080';
      
      // 构建请求数据
      const requestData = {
        roleType: data.role === 'admin' ? 'ADMIN' : 'PARTNER',
        roleName: data.role === 'admin' ? '管理员' : '伴侣',
        adminPassword: data.password
      };
      
      wx.request({
        url: `${baseUrl}/api/user-role/setup`,
        method: 'POST',
        data: requestData,
        header: {
          'Authorization': `Bearer ${wx.getStorageSync('token')}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(res.data?.message || '网络请求失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
});